import axios from "axios";
import router from "@/router";
import { localCache } from "@/utils/cache";
import { ElMessage } from "element-plus";
import { CACHE_TOKEN } from "@/global/constants";
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API, // 基础地址
  timeout: 10000,
});
// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 注入token
    const token = localCache.getCache(CACHE_TOKEN);
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    // if (token) {
    //   config.headers.Authorization = "Bearer" + token;
    // }
    return config;
  },
  (error) => {
    // 失败执行promise
    return Promise.reject(error);
  }
);

// 响应拦截器 处理响应数据和错误处理以及token失效问题
service.interceptors.response.use(
  (response) => {
    // axios默认包裹了data
    // 判断是不是Blob
    if (response.data instanceof Blob) return response.data; // 返回了Blob对象
    const { data, message, success } = response.data; // 默认json格式
    if (success) {
      return data;
    } else {
      ElMessage({ type: "error", message });
      return Promise.reject(new Error(message));
    }
  },
  async (error) => {
    if (error.response.status === 401) {
      ElMessage({ type: "warning", message: "token超时了" });
      // token超时，退出登录
      // await store.dispatch("user/logoutAction");
      // 跳到登录页
      router.push("/login");
      return Promise.reject(error);
    }

    Message({ type: "error", message: error.message });
    return Promise.reject(error);
  }
);

export default service;
